const util = require('../../utils/util');
const UserService = require('../../service/system/user.service');
const bcrypt = require('bcryptjs');
// 获取获取部门树
async function getDeptTree(ctx) {
	try {
		const result = await UserService.getDeptTree();
		util.success(ctx, result);
	} catch (error) {
		util.fail(ctx, `获取部门树失败: ${error.message}`);
	}
}

// 保存用户信息
async function create(ctx) {
	const { userId } = util.decodeToken(ctx);
	const { username, nickname, phone, email, sex, birthday, idCard, logo, accountStatusCd } = ctx.request.body;
	if (!username || !phone) {
		return util.fail(ctx, '用户名和手机号不能为空');
	}
	await UserService.saveUser({ ...ctx.request.body, userId });
	util.success(ctx, '保存用户信息成功');
}

// 获取用户信息
async function getUserInfo(ctx) {
	const { userId } = util.decodeToken(ctx);

	if (!userId) {
		return util.fail(ctx, '用户 ID 未提供或 Token 无效');
	}

	try {
		const userInfo = await UserService.getUserInfo(userId);
		if (!userInfo) {
			return util.fail(ctx, '用户不存在或已被删除');
		}
		util.success(ctx, userInfo);
	} catch (error) {
		util.fail(ctx, `获取用户信息失败: ${error.message}`);
	}
}

// 重置用户密码
async function resetPassword(ctx) {
	const { id } = ctx.request.params;
	if (!id) {
		return util.fail(ctx, '用户id不能为空');
	}
	await UserService.resetPassword(id);
	util.success(ctx, '重置密码成功');
}

// 获取用户列表
async function listUsers(ctx) {
	const { isThisDeep = 'false', deptId = -1, page = 1, limit = 10 } = ctx.query;

	try {
		const result = await UserService.listUsers({
			isThisDeep: isThisDeep === 'true',
			deptId: +deptId,
			page: +page,
			limit: +limit,
		});
		util.success(ctx, result);
	} catch (error) {
		util.fail(ctx, `查询用户列表失败: ${error.message}`);
	}
}

// 修改用户信息
async function updateUser(ctx) {
	const { userId } = util.decodeToken(ctx);
	const { id, username, phone, nickname, logo, age, sex, idCard, email, accountStatusCd, birthday } = ctx.request.body;

	if (!id || isNaN(id)) {
		return util.fail(ctx, '用户 ID 无效');
	}
	if (!username) {
		return util.fail(ctx, '用户名不能为空');
	}

	try {
		const result = await UserService.updateUser({
			id,
			username,
			phone,
			nickname,
			logo,
			age,
			sex,
			idCard,
			email,
			updateId: userId,
			accountStatusCd,
			birthday,
		});
		util.success(ctx);
	} catch (error) {
		util.fail(ctx, `修改用户失败: ${error.message}`);
	}
}

async function getUserRoles(ctx) {
	const { userId } = ctx.query;

	if (!userId) {
		return util.fail(ctx, '用户 ID 无效');
	}

	try {
		const result = await UserService.getUserRoles(+userId);
		util.success(ctx, result);
	} catch (error) {
		util.fail(ctx, `获取用户角色失败: ${error.message}`);
	}
}

async function saveUserRoles(ctx) {
	const { userId, roleIds } = ctx.request.body;

	if (!userId || !Array.isArray(roleIds)) {
		return util.fail(ctx, '用户 ID 或角色 ID 无效');
	}

	try {
		const result = await UserService.saveUserRoles(userId, roleIds);
		util.success(ctx, { userId });
	} catch (error) {
		util.fail(ctx, `保存用户角色失败: ${error.message}`);
	}
}

async function bindUserDepts(ctx) {
	const { userIds, deptIds } = ctx.request.body;

	if (!Array.isArray(userIds) || userIds.length === 0 || !Array.isArray(deptIds)) {
		return util.fail(ctx, '用户 ID 或部门 ID 无效');
	}

	try {
		const result = await UserService.bindUserDepts(userIds, deptIds);
		util.success(ctx, { userIds });
	} catch (error) {
		util.fail(ctx, `绑定用户部门失败: ${error.message}`);
	}
}

async function getUserDataRoles(ctx) {
	const { userId } = ctx.query;

	if (!userId) {
		return util.fail(ctx, '用户 ID 无效');
	}

	try {
		const result = await UserService.getUserDataRoles(+userId);
		util.success(ctx, result);
	} catch (error) {
		util.fail(ctx, `获取用户数据角色失败: ${error.message}`);
	}
}

async function saveUserDataRoles(ctx) {
	const { userId, roleIds } = ctx.request.body;

	if (!userId || !Array.isArray(roleIds)) {
		return util.fail(ctx, '用户 ID 或数据角色 ID 无效');
	}

	try {
		const result = await UserService.saveUserDataRoles(userId, roleIds);
		util.success(ctx, { userId });
	} catch (error) {
		util.fail(ctx, `保存用户数据角色失败: ${error.message}`);
	}
}

async function deleteUsers(ctx) {
	const { ids } = ctx.request.body;

	if (!Array.isArray(ids) || ids.length === 0) {
		return util.fail(ctx, '用户 ID 无效');
	}

	try {
		const result = await UserService.deleteUsers(ids);
		util.success(ctx, { ids });
	} catch (error) {
		util.fail(ctx, `删除用户失败: ${error.message}`);
	}
}

async function getUserById(ctx) {
	const { id } = ctx.params;

	if (!id || isNaN(id)) {
		return util.fail(ctx, '用户 ID 无效');
	}

	try {
		const result = await UserService.getUserById(id);
		util.success(ctx, result);
	} catch (error) {
		util.fail(ctx, `查询用户失败: ${error.message}`);
	}
}

//修改密码
async function updatePassword(ctx) {
	const { userId } = util.decodeToken(ctx);
	const { newPwd, newPwdConfirm, oldPwd } = ctx.request.body;
	if (newPwd !== newPwdConfirm || !newPwd || !newPwdConfirm || !oldPwd) {
		return util.fail(ctx, '密码不能为空');
	}
	const password = await UserService.checkPassword(userId);
	const isMatch = await bcrypt.compare(oldPwd, password.pwd);
	if (!isMatch) {
		return util.fail(ctx, '旧密码不正确');
	}

	try {
		const result = await UserService.updatePassword({ id: userId, newPwd });
		util.success(ctx);
	} catch (error) {
		util.fail(ctx, `修改密码失败: ${error.message}`);
	}
}

module.exports = {
	getDeptTree,
	create,
	listUsers,
	updateUser,
	saveUserDataRoles,
	resetPassword,
	getUserDataRoles,
	getUserRoles,
	saveUserRoles,
	bindUserDepts,
	deleteUsers,
	getUserInfo,
	getUserById,
	updatePassword,
};
